//
//  PlayerViewController.m
//  NewMusic
//
//  Created by dllo on 15/11/13.
//  Copyright © 2015年 Going. All rights reserved.
//

#import "PlayerViewController.h"
#import <STKAudioPlayer.h>
#import "PlayerView.h"
#import "ButtonView.h"
#import "SliderVoiceView.h"
#import "MusicType.h"
#import "CustomerNetworking.h"
#import "SongListView.h"
#import <UIImageView+WebCache.h>
#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>
@interface PlayerViewController ()<ButtonViewDelegate, STKAudioPlayerDelegate, HQSlideViewDelegate, HQSongList>
@property (nonatomic, retain) UIImageView *imageViewBack;
// 开始,结束
@property (nonatomic, retain) UIButton *buttonStart;
// 下一曲
@property (nonatomic, retain) UIButton *buttonNext;
// 上一曲
@property (nonatomic, retain) UIButton *buttonLast;
// 滑条
@property (nonatomic, retain) UISlider *slider;
// 当前时长
@property (nonatomic, retain) UILabel *currentLabel;
// 总时长
@property (nonatomic, retain) UILabel *totalLabel;
// 定时器
@property (nonatomic, retain) NSTimer *timer;
// 动画详情页
@property (nonatomic, retain) PlayerView *playView;
// 记录运行状态
@property (nonatomic, retain) NSString *CurrentState;
// 音量界面
@property (nonatomic, retain) SliderVoiceView *sliderView;
// 音量定时器
@property (nonatomic, retain) NSTimer *volTimer;
// 歌单列表
@property (nonatomic, retain) SongListView *songList;
// 列表数组
@property (nonatomic, retain) NSMutableArray *songArray;
// 暂存歌曲URL
@property (nonatomic, copy) NSString *playerUrl;
@end

@implementation PlayerViewController

- (void)dealloc
{
    [_imageViewBack release];
    [_buttonLast release];
    [_buttonNext release];
    [_buttonStart release];
    [_slider release];
    [_currentLabel release];
    [_totalLabel release];
    [_player release];
    [_musicArr release];
    [_timer release];
    [_playView release];
    [_CurrentState release];
    [_sliderView release];
    [_volTimer release];
    [_playerUrl release];
    [_songList release];
    [super dealloc];
}

+ (PlayerViewController *)sharePlayerViewController
{
    static PlayerViewController *player = nil;
    static dispatch_once_t once;
    if (nil == player)
    {
        dispatch_once(&once, ^{
            player = [PlayerViewController new];
            [player viewDidLoad];
        });
    }
    return player;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 歌曲位置
    self.musicNum = 0;
    self.songArray = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    NSString *local = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [local stringByAppendingString:@"/music.txt"];
    self.musicArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];    
    // 创建item
    [self creatNav];
    // 创建背景
    [self creatBackGroud];
    // 创建View
    [self creatPlayerView];
    // 创建buttonView
    [self creatButtonView];
    // 创建button
    [self creatButton];
    // 创建进程轴
    [self creatSliderButton];
    // 创建音频
    [self creatSTKplayer];
    // 选择执行状态
    [self GetTurn];
    // 创建歌单列表
    [self getMusicList];
}
#pragma 创建音频
- (void)creatSTKplayer
{
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    CGFloat volNum = [user floatForKey:@"voice"];
    self.player.volume = volNum;
    self.player.delegate = self;
    self.player.meteringEnabled = YES;
}
#pragma 创建进程轴
- (void)creatSliderButton
{
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 130, 480, 260, 20)];
    self.slider.value = 0;
    self.slider.maximumTrackTintColor = [UIColor colorWithRed:200 / 255.0 green:200 / 255.0 blue:200 / 255.0 alpha:1.0];
    self.slider.minimumTrackTintColor = [UIColor colorWithRed:59 / 255.0 green:142 / 255.0 blue:89 / 255.0 alpha:1.0];
    [self.slider setThumbImage:[UIImage imageNamed:@"BF-anniu"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    [_slider release];
    
    self.currentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.slider.frame.origin.y - 3, 57, 25)];
    self.currentLabel.text = @"0:00";
    self.currentLabel.font = [UIFont fontWithName:@"ArialMT" size:16];
    self.currentLabel.textAlignment = NSTextAlignmentCenter;
    self.currentLabel.textColor = [UIColor colorWithRed:230 / 255.0 green:230 / 255.0 blue:230 / 255.0 alpha:1.0];
    [self.view addSubview:self.currentLabel];
    [_currentLabel release];
    
    self.totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 130, self.slider.frame.origin.y - 3, 57, 25)];
    self.totalLabel.text = @"0:00";
    self.totalLabel.font = [UIFont fontWithName:@"ArialMT" size:16];
    self.totalLabel.textAlignment = NSTextAlignmentCenter;
    self.totalLabel.textColor = [UIColor colorWithRed:230 / 255.0 green:230 / 255.0 blue:230 / 255.0 alpha:1.0];
    [self.view addSubview:self.totalLabel];
    [_totalLabel release];
    
}
#pragma 播放器音乐赋值
- (void)playerMusic
{
    NSDictionary *dic = self.musicArr[self.musicNum];
    NSArray *arr = [dic objectForKey:@"music"];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"MusicType"];
    for (MusicType *music in arr)
    {
        if ([music.typeDescription isEqual:str])
        {
            self.playerUrl = music.url;
            continue;
        } else {
            self.playerUrl = music.url;
        }
    }
    self.playView.labelName.text = [dic objectForKey:@"songerName"];
    self.playView.labelSonger.text = [NSString stringWithFormat:@"歌手:%@", [dic objectForKey:@"songerName"]];
    self.navigationItem.title = [dic objectForKey:@"name"];
    self.playView.labelalbum.text = [NSString stringWithFormat:@"专辑:%@", [dic objectForKey:@"album"]];
    [self getMusic:[dic objectForKey:@"id"]  and:[dic objectForKey:@"songerName"]];
    [self.player play:self.playerUrl];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(change) userInfo:nil repeats:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"statePlayer" object:nil];
}
- (void)getMusic:(NSString *)songid
             and:(NSString *)name
{
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://so.ard.iyyin.com/s/pic?singerid=%@&artist=%@", [songid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] andParameters:nil andBlock:^(id response) {
        NSArray *arr = [response objectForKey:@"data"];
        NSDictionary *dic = arr.lastObject;
        NSArray *arrM = [dic objectForKey:@"picUrls"];
        self.picUrl = [arrM.firstObject objectForKey:@"picUrl"];
        self.labelText = self.navigationItem.title;
        [self.imageViewBack sd_setImageWithURLStr:self.picUrl];
        [self.playView.imageViewDisc sd_setImageWithURLStr:self.picUrl];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLabelAndImageView" object:nil];
    }];
}
#pragma 定时器方法(定时器只负责限时时间进度条等)
- (void)change
{
    self.totalLabel.text = [NSString stringWithFormat:@"%ld:%.2ld", (NSInteger)self.player.duration / 60, (NSInteger)self.player.duration % 60];
    self.currentLabel.text = [NSString stringWithFormat:@"%ld:%.2ld", (NSInteger)self.player.progress / 60, (NSInteger)self.player.progress % 60];
    self.slider.minimumValue = 0;
    self.slider.maximumValue = self.player.duration;
    self.slider.value = self.player.progress;
}
// 触发时机, 每首歌曲开始播放
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    //    NSLog(@"开始播放");
    [self animationWithPlayer];
}
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    //    NSLog(@"完成加载");
}
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    //    NSLog(@"播放状态改变");
}
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    // 结束移除所有动画
    [self.playView.imageViewDiscBack.layer removeAllAnimations];
    if ([self.CurrentState isEqual:@"列表"])
    {
        if ((self.musicNum == self.musicArr.count - 1) && (self.player.state == STKAudioPlayerStateStopped))
        {
            self.musicNum = 0;
            [self changeMusic];
        }
        if (self.player.state == STKAudioPlayerStateStopped)
        {
            self.musicNum++;
            [self changeMusic];
        }
    } else if ([self.CurrentState isEqual:@"单曲"]) {
        if (self.player.state == STKAudioPlayerStateStopped)
        {
            [self changeMusic];
        }
    } else {
        if (self.player.state == STKAudioPlayerStateStopped)
        {
            self.musicNum = (NSInteger)arc4random() % self.musicArr.count;
            [self changeMusic];
        }
    }
}
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
    self.buttonStart.selected = NO;
}
#pragma button监听方法
- (void)buttonAction:(UIButton *)sender
{
    if (sender == self.buttonStart)
    {
        if (STKAudioPlayerStatePlaying == self.player.state)
        {
            sender.selected = !sender.selected;
            [self.player pause];
            [self animationStop];
        } else if (self.player.state == STKAudioPlayerStatePaused) {
            sender.selected = !sender.selected;
            [self.player resume];
            [self animationResume];
        } else {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                sender.selected = !sender.selected;
                [self playerMusic];
            });
        }
    } else if (sender == self.buttonLast) {
        self.buttonStart.selected = YES;
        [self animationResume];
        if ([self.CurrentState isEqual:@"随机"])
        {
            self.musicNum = (NSInteger)arc4random() % self.musicArr.count;
            [self changeMusic];
        } else {
            if (0 == self.musicNum)
            {
                self.musicNum = self.musicArr.count - 1;
                [self changeMusic];
            } else {
                self.musicNum--;
                [self changeMusic];
            }
        }
    } else {
        self.buttonStart.selected = YES;
        [self animationResume];
        if ([self.CurrentState isEqual:@"随机"])
        {
            self.musicNum = (NSInteger)arc4random() % self.musicArr.count;
            [self changeMusic];
        } else {
            if (self.musicArr.count - 1 == self.musicNum)
            {
                self.musicNum = 0;
                [self changeMusic];
            } else {
                self.musicNum++;
                [self changeMusic];
            }
        }
    }
}
#pragma 更换歌曲执行方法
- (void)changeMusic
{
    [UIView animateWithDuration:0.5 animations:^{
        self.playView.imageViewDisc.frame = CGRectMake(10, -300, 280, 280);
    } completion:^(BOOL finished) {
        self.playView.imageViewDisc.frame = CGRectMake(10, 320, 280, 280);
        [UIView animateWithDuration:0.5 animations:^{
            self.playView.imageViewDisc.frame = CGRectMake(10, 10, 280, 280);
        }];
    }];
    [self.player clearQueue];
    [self.timer invalidate];
    self.timer = nil;
    [self playerMusic];
    self.slider.value = 0;
    self.currentLabel.text = @"0:00";
    self.totalLabel.text = @"0:00";
}
#pragma 进程轴监听
- (void)sliderAction:(UISlider *)sender
{
    [self.player seekToTime:sender.value];
}
#pragma 创建button
- (void)creatButton
{
    self.buttonStart = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonStart.frame = CGRectMake(self.view.frame.size.width / 2 - 40, 510, 80, 80);
    [self.buttonStart setImage:[UIImage imageNamed:@"BF-bofang"] forState:UIControlStateNormal];
    [self.buttonStart setImage:[UIImage imageNamed:@"BF-zhanting"] forState:UIControlStateSelected];
    [self.buttonStart addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.buttonStart.layer.cornerRadius = 40;
    [self.view addSubview:self.buttonStart];
    
    self.buttonLast = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonLast.frame = CGRectMake(70, self.buttonStart.frame.origin.y + 10, 60, 60);
    self.buttonLast.layer.cornerRadius = 30;
    [self.buttonLast setImage:[UIImage imageNamed:@"BF-shangyiqu"] forState:UIControlStateNormal];
    [self.buttonLast addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonLast];
    
    self.buttonNext = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonNext.frame = CGRectMake(245, self.buttonStart.frame.origin.y + 10, 60, 60);
    self.buttonNext.layer.cornerRadius = 30;
    [self.buttonNext setImage:[UIImage imageNamed:@"BF-xiayiqu"] forState:UIControlStateNormal];
    [self.buttonNext addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonNext];
}
#pragma 创建动画
- (void)animationWithPlayer
{
    CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    basic.fromValue = @(0);
    basic.toValue = @(M_PI * 2);
    basic.duration = 15;
    basic.cumulative = YES;
    basic.repeatCount = HUGE_VALF;
    [self.playView.imageViewDiscBack.layer addAnimation:basic forKey:nil];
}
#pragma 暂停动画
- (void)animationStop
{
    CALayer *layer = self.playView.imageViewDiscBack.layer;
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0;
    layer.timeOffset = pausedTime;
}
#pragma 继续动画
- (void)animationResume
{
    CALayer *layer = self.playView.imageViewDiscBack.layer;
    CFTimeInterval pauseTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSince = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pauseTime;
    layer.beginTime = timeSince;
}
#pragma 创建5大功能
- (void)creatButtonView
{
    ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(0, 600, self.view.frame.size.width, 50)];
    buttonView.delegate = self;
    buttonView.userInteractionEnabled = YES;
    [self.imageViewBack addSubview:buttonView];
    [buttonView release];
}
#pragma 创建playerView
- (void)creatPlayerView
{
    self.playView = [[PlayerView alloc] initWithFrame:CGRectMake(0, 20, 375, 420) imageViewUrl:nil songerName:nil album:nil];
    self.playView.userInteractionEnabled = YES;
    [self.imageViewBack addSubview:self.playView];
    [self.playView addSubview:self.sliderView];
    [_playView release];
}
#pragma 背景创建
- (void)creatBackGroud
{
    self.imageViewBack = [[UIImageView alloc] initWithFrame:self.view.frame];
    self.imageViewBack.userInteractionEnabled = YES;
    [self.view addSubview:self.imageViewBack];
    [_imageViewBack release];
    //创建毛玻璃
    UIVisualEffectView *sual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    sual.userInteractionEnabled = YES;
    sual.alpha = 0.8;
    sual.frame = self.view.frame;
    [self.imageViewBack addSubview:sual];
    [sual release];
}
#pragma 导航创建
- (void)creatNav
{
    self.navigationItem.title = @"用心聆听音乐";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-xia"] style:UIBarButtonItemStylePlain target:self action:@selector(barLeft)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:200 / 255.0 green:200 / 255.0 blue:200 / 255.0 alpha:1.0];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-dian"] style:UIBarButtonItemStylePlain target:self action:@selector(barright)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:200 / 255.0 green:200 / 255.0 blue:200 / 255.0 alpha:1.0];
}
#pragma 回跳
- (void)barLeft
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma 弹出调节音量
- (void)barright
{
    [UIView animateWithDuration:0.5 animations:^{
        self.sliderView.frame = CGRectMake(325, 30, 50, 420);
    }];
    self.volTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(VolChange) userInfo:nil repeats:NO];
}
#pragma 音量界面回弹
- (void)VolChange
{
    [UIView animateWithDuration:0.5 animations:^{
        self.sliderView.frame = CGRectMake(375, 30, 50, 420);
    }];
}
#pragma 音量界面触发方法
- (void)VolSliderAction:(CGFloat)value
{
    self.player.volume = value;
    [self.volTimer invalidate];
    self.volTimer = nil;
    self.volTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(VolChange) userInfo:nil repeats:NO];
}
- (void)shareInPlayerView
{
    NSLog(@"分享");
}
- (void)GetListView
{
    [UIView animateWithDuration:0.5 animations:^{
        self.songList.frame = CGRectMake(0, 367, 375, 300);
    }];
}
- (void)returnMusicList:(NSString *)num
{
    if (nil != num)
    {
        self.musicNum = [num integerValue];
        [self changeMusic];
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.songList.frame = CGRectMake(0, 667, 375, 300);
    }];
}
- (void)GetSonging
{
    NSLog(@"唱歌");
}
- (void)getMusicList
{
    self.songList = [[SongListView alloc] initWithFrame:CGRectMake(0, 667, 375, 300)];
    self.songList.delegate = self;
    self.songList.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.songList];
    [_songList release];
}
- (SliderVoiceView *)sliderView
{
    if (nil == _sliderView)
    {
        self.sliderView = [[SliderVoiceView alloc] initWithFrame:CGRectMake(375, 30, 50, 420)];
        self.sliderView.delegate = self;
        [_sliderView release];
    }
    return _sliderView;
}
- (void)GetTurn
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"turn"];
    if ([str isEqual:@"list"])
    {
        NSLog(@"列表");
        self.CurrentState = @"列表";
    } else if ([str isEqual:@"only"]) {
        NSLog(@"单曲");
        self.CurrentState = @"单曲";
    } else {
        NSLog(@"随机");
        self.CurrentState = @"随机";
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [[self findHairlineImageViewUnder:self.navigationController.navigationBar] setHidden:YES];
    [super viewDidAppear:animated];
    if (STKAudioPlayerStatePaused == self.player.state || STKAudioPlayerStateStopped == self.player.state)
    {
        [self animationWithPlayer];
        [self animationStop];
        self.buttonStart.selected = NO;
        NSLog(@"paun");
    }
    if (STKAudioPlayerStatePlaying == self.player.state)
    {
        [self animationWithPlayer];
        self.buttonStart.selected = YES;
        NSLog(@"play");
    }
}
- (void)stopMusic
{
    if (STKAudioPlayerStatePlaying == self.player.state)
    {
        [self.player pause];
    }
}
- (void)StartMusic
{
    if (STKAudioPlayerStatePaused == self.player.state)
    {
        [self.player resume];
    } else {
        [self playerMusic];
    }
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
- (void)MusicStart:(NSInteger)num
{
    [self.songArray removeAllObjects];
    NSDictionary *dic = self.musicArr[num];
    NSArray *arr = [dic objectForKey:@"music"];
    NSString *url = nil;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"MusicType"];
    for (MusicType *music in arr)
    {
        if ([music.typeDescription isEqual:str])
        {
            url = music.url;
            break;
        } else {
            url = music.url;
        }
    }
    if (![self.playerUrl isEqual:url])
    {
        self.musicNum = num;
        [self buttonAction:self.buttonStart];
        [self changeMusic];
        for (NSDictionary *dic in self.musicArr)
        {
            [self.songArray addObject:[NSString stringWithFormat:@"%@    %@", [dic objectForKey:@"name"], [dic objectForKey:@"songerName"]]];
        }
        [self.songList setDataArrayWith:self.songArray];
    }
    [self animationWithPlayer];
    [self animationResume];
    
    NSString *local = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [local stringByAppendingString:@"/music.txt"];
    NSLog(@"%@", filePath);
    [NSKeyedArchiver archiveRootObject:self.musicArr toFile:filePath];
}
- (void)changeNumWith:(BOOL)change
{
    if (change)
    {
        [self buttonAction:self.buttonLast];
    } else {
        [self buttonAction:self.buttonNext];
    }
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self returnMusicList:nil];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"changeControlView" object:self userInfo:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
